package org.example.ReflectDemo.lang;

import org.example.ReflectDemo.lang.reflect.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClassDemo {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
       reflectNewInstance();
    reflectPrivateConstructor();
    reflectPrivateField();
    reflectPrivateMethod();
    }
    public static void reflectNewInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        Class classStudent=Class
                .forName("org.example.ReflectDemo.lang.reflect.Student");
        //创建实例
        Object objectStudent=classStudent.newInstance();
        Student student=(Student)objectStudent;
        System.out.println("获取学生对象:"+student);
    }
    //反射私有的构造⽅法 屏蔽内容为获得公有的构造⽅法
    public static void reflectPrivateConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class classStudent=Class
                .forName("org.example.ReflectDemo.lang.reflect.Student");
        Constructor declaredConstructorStudent=classStudent
                .getDeclaredConstructor(String.class,int.class);
        //设置为true后可修改访问权限
        declaredConstructorStudent.setAccessible(true);
        Object objectStudent=declaredConstructorStudent
                .newInstance("李四",20);

    }
    // 反射私有属性
    public static void reflectPrivateField() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class classStudent=Class
                .forName("org.example.ReflectDemo.lang.reflect.Student");
        Field field=classStudent.getDeclaredField("name");
        field.setAccessible(true);
        Object objectStudent=classStudent.newInstance();
        Student student=(Student)objectStudent;
        field.set(student,"王五");
        String name= (String) field.get( student);
        System.out.println("获取属性值:"+name);
    }
    // 反射私有⽅法
    public static void reflectPrivateMethod() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class classStudent=Class
                .forName("org.example.ReflectDemo.lang.reflect.Student");
        Method methodStudent=classStudent
                .getDeclaredMethod("function",String.class);
        System.out.println("获取私有⽅法:"+methodStudent);
        methodStudent.setAccessible(true);
        Object objectStudent=classStudent.newInstance();
        methodStudent.invoke(objectStudent,"hello");
    }
}
